<template>
  <div class="user-add">
    <el-row>
      <el-col :span="12">
        <!--        表单-->
        <el-form ref="ruleForm" :model="form" label-width="80px" :rules="rules">
          <!--          上级菜单-->
          <el-form-item label="一级分类" prop="first_cateid">
            <el-select v-model="form.first_cateid" placeholder="请选择" @change="handleChangeCategory">
              <el-option
                v-for="item of categoryList" :key="item.id"
                v-if="item.catename != form.catename"
                :value="item.id" :label="item.catename" ></el-option>
            </el-select>
          </el-form-item>
          <!--          上级菜单-->
          <el-form-item label="二级分类" prop="second_cateid">
            <el-select v-model="form.second_cateid" placeholder="请选择">
              <el-option
                v-for="item of secondCategory" :key="item.id"
                :value="item.id" :label="item.catename" ></el-option>
            </el-select>
          </el-form-item>
          <!--          title-->
          <el-form-item label="商品名称" prop="goodsname">
            <el-input v-model="form.goodsname"></el-input>
          </el-form-item>
          <!--          price-->
          <el-form-item label="价格" prop="price">
            <el-input v-model="form.price"></el-input>
          </el-form-item>
          <!--          market_price-->
          <el-form-item label="市场价格" prop="market_price">
            <el-input v-model="form.market_price"></el-input>
          </el-form-item>
          <!--          图片-->
          <el-form-item label="图片">
            <el-upload
              :auto-upload="false"
              action="#"
              list-type="picture-card"
              :on-change="fileChange"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :file-list="imgUrlList"
              :limit="1"
              :on-exceed="limitCount"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" size="tiny">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
          <!--          商品规格-->
          <el-form-item label="商品规格" prop="specsid">
            <el-select v-model="form.specsid" placeholder="请选择" @change="handleChangeSepcs">
              <el-option
                v-for="item of specsList" :key="item.id"
                v-if="item.specsname != form.catename"
                :value="item.id" :label="item.specsname" ></el-option>
            </el-select>
          </el-form-item>
          <!--          规格属性-->
          <el-form-item label="规格属性" prop="specsattr">
            <el-select v-model="form.specsattr" placeholder="请选择" :multiple="true">
              <el-option
                v-for="(item,index) of secondSepcs" :key="item.id"
                :value="item" :label="item" ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否新品">
            <el-switch
              v-model="form.isnew"
              :active-value="1"
              :inactive-value="0"
              active-color="#f00"
              inactive-color="#eee"
            ></el-switch>
          </el-form-item>
          <el-form-item label="是否热卖">
            <el-switch
              v-model="form.ishot"
              :active-value="1"
              :inactive-value="0"
              active-color="#f00"
              inactive-color="#eee"
            ></el-switch>
          </el-form-item>
<!--          描述-->
          <el-form-item label="商品描述">
            <div id="div1" >
            </div>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch
              v-model="form.status"
              :active-value="1"
              :inactive-value="2"
              active-color="#f00"
              inactive-color="#eee"
            ></el-switch>
          </el-form-item>
          <el-form-item v-if="typeof $route.params.id == 'undefined'">
            <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
          </el-form-item>
          <el-form-item v-else>
            <el-button type="primary" @click="submitForm('ruleForm')">确认修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import E from "wangeditor";

  import { mapState, mapActions } from 'vuex'
  export default {
    name: "vUserAdd",
    mounted() {
      //实例化富文本编辑器
      this.editor = new E("#div1");
      this.editor.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'justify',
        'quote',
        'emoticon',
        'image',
        'video',
        'table',
        'code',
        'splitLine',
        'undo',
        'redo',
      ]
      this.editor.config.zIndex = 1
      this.editor.create();
      //请求商品详情 判断是否有id参数
      if (this.$route.params.id) {//有
        this.axios({
          url: '/api/goodsinfo',
          params: {id: this.$route.params.id},
          method: 'get'
        }).then(res => {//请求成功后
          console.log(res.list,'商品详情------')
          this.form = res.list
          //初始化二级分类
          let currentCategory = this.categoryList.filter(item => {
            return item.id == this.form.first_cateid
          })
          this.secondCategory = currentCategory[0].children//取出规格中对应的属性
          //初始化二级规格属性
          if (this.form.specsattr.indexOf(',') == -1) {
            this.form.specsattr = [this.form.specsattr]
          }else{
            this.form.specsattr = this.form.specsattr.split(',')
          }
          console.log(this.form.specsattr,'33333333------');
          let currentSepcs = this.specsList.filter(item => {
            return item.id == this.form.specsid
          })
          this.secondSepcs = currentSepcs[0].attrs
          console.log(this.secondSepcs,11111)



          // this.updatecategory({pid: this.form.first_cateid})//初始化二级分类
          this.form.id = this.$route.params.id//手动添加id
          if (res.list.img.trim() != '') {//判断是否有图片
            this.imgUrlList.push({url: res.list.img})//手动初始化
          }
          if(this.form.description) {//初始化富文本
            this.editor.txt.html(this.form.description)
          }
        })
      }
      // this.updatecategory({pid: 0})//请求一级分类
      this.updatecategory()//请求一级分类
      this.updatespecs({})//请求一级规格
    },
    data() {
      return {
        form: {status:1},
        rules: {
          first_cateid: [
            {required: true, message: '请选择一级分类', trigger: 'blur'}
          ],
          second_cateid: [
            {required: true, message: '请选择二级分类', trigger: 'blur'}
          ],
          goodsname: [
            {required: true, message: '请输入商品名称', trigger: 'blur'}
          ],
          specsid: [
            {required: true, message: '请选择规格', trigger: 'blur'}
          ],
          specsattr: [
            {required: true, message: '请选择规格属性  ', trigger: 'blur'}
          ],
          market_price: [
            {required: true, message: '请输入市场价格', trigger: 'blur'}
          ],
          price: [
            {required: true, message: '请输入价格', trigger: 'blur'}
          ],
        },
        //处理图片数据
        dialogImageUrl: '',
        dialogVisible: false,
        imgUrlList:[],
        editor: '',//富文本默认美容
        secondCategory: [],//二级分类
        secondSepcs: []//二级规格属性
      }
    },
    computed: {
      ...mapState(['categoryList',"specsList"])
    },
    methods: {
      ...mapActions(['updatecategory','updatespecs']),
      //选中一级规格时
      handleChangeSepcs(id) {
        delete this.form.specsattr //清空二级规格属性内容
        let currentSepcs = this.specsList.filter(item => {//过滤出当前规格
             return item.id == id
        })
        this.secondSepcs = currentSepcs[0].attrs//取出规格中对应的属性
      },
      //选中分类一时
      handleChangeCategory(id) {
        delete this.form.second_cateid //清除二级分类中的内容
        let currentCategory = this.categoryList.filter(item => {
          return item.id == id
        })
        this.secondCategory = currentCategory[0].children
      },
      //清除图片
      handleRemove(file, fileList) {
        console.log(file, fileList,'当前文件  和 文件列表');
        //清除
        this.form.img = ''
      },
      //处理图片上传问题
      fileChange (file, fileList) {
        this.form.img = file.raw
      },
      //图片大于二张时
      limitCount() {
        this.$message({
          type: 'success',
          message: '图片只能上传一张'
        });
      },
      //图片放大功能
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      //提交表单功能
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('确定添加/修改该商分类?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.form.specsattr = this.form.specsattr.join(',')
              this.form.description = this.editor.txt.html() //手动记录富文本内容
              let url = this.$route.params.id?'/api/goodsedit': '/api/goodsadd'
              //序列化表单
              let data = new FormData()
              for(let key in this.form) {
                data.append(key,this.form[key])
              }
              //发送数据
              this.axios({
                method: 'post',
                url:url,
                data: data
              }).then(res => {
                if (res.code == 200) {//发送成功后
                  this.$store.dispatch('updatagoods')//更新goodsList
                  this.$message({
                    type: 'success',
                    message: res.msg
                  });
                  this.$router.go(-1)
                } else {
                  this.$message({
                    type: 'success',
                    message: res.msg
                  });
                }
              })
            })
              .catch(() => {
                this.$message({
                  type: 'info',
                  message: '取消操作'
                });
              });
          } else {
            this.$message({
              type: 'info',
              message: '信息填写错误'
            });
            return false;
          }
        });
      }
    }
  }
</script>

<style scoped>
  #div1{
    min-width: 600px;
  }
  .w-e-toolbar,
  .w-e-text-container{
    z-index: 1 !important;
  }
</style>
